package com.genntii.examManager.controller;

import com.genntii.examManager.common.constant.CommonConstant;
import com.genntii.examManager.common.result.PageResult;
import com.genntii.examManager.common.result.Result;
import com.genntii.examManager.domain.question.dto.ExamResult;
import com.genntii.examManager.domain.question.vo.ExamDetailVO;
import com.genntii.examManager.domain.vo.ExamRecordVO;
import com.genntii.examManager.domain.vo.ExamVO;
import com.genntii.examManager.service.ExamRecordService;
import com.genntii.examManager.service.ExamService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

@RequestMapping("/exam")
@RestController
public class ExamController {

    @Resource
    private ExamService examService;

    @Resource
    private ExamRecordService examRecordService;

    @GetMapping("/list")
    public Result<PageResult<ExamVO>> getExamList(@RequestParam("pageNum") Integer pageNum,
                                                  @RequestParam("pageSize") Integer pageSize,
                                                  @RequestParam("courseId") Long courseId,
                                                  HttpServletRequest request){
        Long userId = request.getAttribute(CommonConstant.USER_ID) != null ? Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.USER_ID))) : Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.TEACHER_ID)));
        return Result.success(examService.getExamList(pageNum,pageSize,userId,courseId));
    }

    @GetMapping("/{examId}")
    public Result<ExamDetailVO> exam(@PathVariable Long examId,
                                     HttpServletRequest request){
        Long userId = Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.USER_ID)));
        return Result.success(examService.getExam(examId, userId));
    }

    @GetMapping("/history")
    public Result<PageResult<ExamRecordVO>> getHistoryList(@RequestParam("pageNum") Integer pageNum,
                                                          @RequestParam("pageSize") Integer pageSize,
                                                          HttpServletRequest request){
        Long userId = Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.USER_ID))) ;
        return Result.success(examRecordService.getExamHistory(pageNum,pageSize,userId));
    }

    @PostMapping
    public Result commit(@RequestBody ExamResult examResult, HttpServletRequest request){
        Long userId = Long.valueOf(String.valueOf(request.getAttribute(CommonConstant.USER_ID))) ;
        examRecordService.examCommit(examResult,userId);
        return Result.success();
    }

    @GetMapping("/history/{examRecordId}")
    public Result<ExamResult> historyHistory(@PathVariable Long examRecordId){
        return Result.success(examRecordService.getExamResult(examRecordId));
    }
}
